﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Reviewer.Entities.Services;
using Reviewer.Entities;
using Reviewer.Business;

public partial class CMSV2_Controls_Game_GameInfo : System.Web.UI.UserControl
{
    public Guid GameId
    {
        get;
        set;
    }

    public Format[] SelectedFormats()
    {
        return this.uiGfGameFormats.SelectedFormats();
    }

    public void Refresh()
    {
        this.InitializeGenres();
        Game[] games = null;
        if (this.GameId != Guid.Empty)
        {
            using (IGameService service = ServiceFactory.GameService)
            {
                games = service.GetBy(this.GameId).OrderBy(t => t.Id).ToArray();
                this.uiGfGameFormats.Games = games;

                if (games != null && games.Length > 0)
                {
                    this.uiTxtTitle.Text = games[0].Title;

                    ListItem selectedItem = this.uiDdlGenre.Items.FindByValue(games[0].Genre.ToString());
                    if (selectedItem != null)
                    {
                        selectedItem.Selected = true;
                    }

                    uiBtnDelete.Enabled = true;

                    return;
                }
            }
        }
        Clear();
        this.uiGfGameFormats.Games = games;
    }

    public void Clear()
    {
        this.uiTxtTitle.Text = String.Empty;
        this.uiBtnDelete.Enabled = false;
        this.uiGfGameFormats.Games = new Game[0];
    }

    protected void Page_Load(object sender, EventArgs e)
    {
    }

    private void InitializeGenres()
    {
        using (IMetadataService<Genre> service = ServiceFactory.GetMetadataService<Genre>())
        {
            this.uiDdlGenre.DataSource = service.GetAll();
            this.uiDdlGenre.DataTextField = "Name";
            this.uiDdlGenre.DataValueField = "Id";
            this.uiDdlGenre.DataBind();
        }
    }


    protected void uiBtnSave_Click(object sender, EventArgs e)
    {
        Page.Validate();
        if (Page.IsValid)
        {
            List<Game> gameInstances = new List<Game>();

            bool isNewInstance = true;

            if (!this.GameId.Equals(Guid.Empty))
            {
                using (IGameService service = ServiceFactory.GameService)
                {
                    gameInstances.AddRange(service.GetBy(this.GameId));
                }
                isNewInstance = false;
            }

            Format[] selectedFormats = this.uiGfGameFormats.SelectedFormats();
            //Step 1: Remove formats that are no longer used.
            int index = 0;
            while (index < gameInstances.Count)
            {
                int instanceFormat = gameInstances[index].Format;
                Format forma = selectedFormats.FirstOrDefault(t => t.Id.Equals(instanceFormat));

                if (forma == null)
                {
                    Game removedGame = gameInstances[index];
                    gameInstances.RemoveAt(index);

                    using (IGameAdminService adminService = ServiceFactory.GameAdminService)
                    using (IGameService service = ServiceFactory.GameService)
                    {
                        GameScreenshot[] screenshots = service.GetAssociatedScreenshots(this.GameId);
                        GameScreenshot[] thisFormatScreenshots = screenshots.Where(t => t.Format.Equals(Convert.ToInt32(removedGame.Format))).ToArray();
                        foreach (GameScreenshot shot in thisFormatScreenshots)
                        {
                            adminService.DeleteAssociatedScreenshotBy(shot.Id);
                            if (screenshots.Count(t => t.FileName.ToUpperInvariant().Equals(shot.FileName.ToUpperInvariant(), StringComparison.OrdinalIgnoreCase)) == 1)
                            {
                                string filename = ResolveUrl("~/screenshots/" + shot.FileName);
                                if (System.IO.File.Exists(MapPath(filename)))
                                {
                                    System.IO.File.Delete(MapPath(filename));
                                }
                            }
                        }

                        string coverFilename = ResolveUrl("~/covers/" + this.GameId.ToString() + "_" + removedGame.Format.ToString() + ".");
                        if (System.IO.File.Exists(MapPath(coverFilename + "png")))
                        {
                            System.IO.File.Delete(MapPath(coverFilename + "png"));
                        }
                        else if (System.IO.File.Exists(MapPath(coverFilename + "jpg")))
                        {
                            System.IO.File.Delete(MapPath(coverFilename + "jpg"));
                        }
                    }
                }
                else
                {
                    index++;
                }
            }

            //Step 2: Add formats that are not in the list
            foreach (Format format in selectedFormats)
            {
                if (!gameInstances.Exists(t => t.Format.Equals(format.Id)))
                {
                    Game newGame = new Game();
                    newGame.GameId = this.GameId;
                    newGame.Format = format.Id;
                    gameInstances.Add(newGame);
                }
            }

            //Step 3: Update data
            foreach (Game game in gameInstances)
            {
                game.Title = uiTxtTitle.Text;
                game.Genre = Convert.ToInt32(uiDdlGenre.SelectedValue);
                game.ReleaseDate = this.uiGfGameFormats.GetReleaseDate(game.Format);
                game.ReleaseDateFormat = this.uiGfGameFormats.GetReleaseDateFormat(game.Format);
                game.Publisher = this.uiGfGameFormats.GetPublisher(game.Format);
                game.Developer = this.uiGfGameFormats.GetDeveloper(game.Format);
                game.MultiplayerInfo = this.uiGfGameFormats.GetMultiplayerInfo(game.Format);
            }

            using (IGameAdminService adminService = ServiceFactory.GameAdminService)
            {
                Game[] savedGames = adminService.Save(gameInstances.ToArray());

                if (this.GameId.Equals(Guid.Empty))
                {
                    Response.Redirect(Request.Url + "?GameID=" + savedGames[0].GameId.ToString());
                }
            }

            if (isNewInstance)
            {
                UriHandler.ClearGamesDirectory();
            }
        }
    }
    protected void uiBtnDelete_Click(object sender, EventArgs e)
    {
        if (!this.GameId.Equals(Guid.Empty))
        {
            using (IGameAdminService adminService = ServiceFactory.GameAdminService)
            {
                adminService.Delete(this.GameId);
                Response.Redirect("Default.aspx");
            }
        }
    }
}
